<template>
	  <view>
	  	 <view class="count_box">
			<view class="count_item_box">
				{{ hours }}
			</view>小时
			<view class="count_item_box">
				{{ minutes }}
			</view>分钟
			<view class="count_item_box">
				{{ seconds }}
			</view>秒
	  	 </view>
	  </view>
</template>

<script>
export default {
  props: {
    targetDate: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      countdownInterval: null,
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0
    };
  },
  mounted() {
    this.startCountdown();
  },
  beforeDestroy() {
    clearInterval(this.countdownInterval);
  },
  methods: {
    startCountdown() {
      this.updateCountdown(); // 先立即更新一次
      this.countdownInterval = setInterval(() => {
        this.updateCountdown();
      }, 1000);
    },
    updateCountdown() {
      const now = new Date();
      const target = new Date(this.targetDate);
      const duration = Math.max(0, target - now) / 1000;

      this.days = Math.floor(duration / 86400) < 10 ?'0'+Math.floor(duration / 86400):Math.floor(duration / 86400);
      this.hours = Math.floor((duration % 86400) / 3600) < 10 ?'0'+Math.floor((duration % 86400) / 3600) : Math.floor((duration % 86400) / 3600);
      this.minutes = Math.floor((duration % 3600) / 60) < 10 ?'0'+Math.floor((duration % 3600) / 60):Math.floor((duration % 3600) / 60);
      this.seconds = Math.floor(duration % 60) < 10 ?'0'+ Math.floor(duration % 60):Math.floor(duration % 60);
	  
      if (duration <= 0) {
        clearInterval(this.countdownInterval);
        this.$emit('countdownFinished'); // 触发倒计时结束事件
      }
    }
  }
};
</script>
<style lang="scss">
	.count_box{
		display: flex;
		align-items: center;
		.count_item_box{
			padding: 6rpx 10rpx;
			font-size: 11px;
			border-radius: 10rpx;
		    color: #333;
			margin:0 2rpx;
		}
	}
</style>
